package com.wing.storage.Controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.response.ProductVO;
import com.wing.product.model.response.WarehouseSkuExportVO;
import com.wing.storage.model.response.WarehouseSkuItermVo;
import com.wing.storage.service.WarehouseAreaSkuItermService;
import com.wing.utils.ExcelUtils;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.WarehouseSkuItermExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 库位存货明细管理-Controller
 *
 */
@Validated
@Api(value = "库位存货明细管理", tags = "#/storage/warehouseSkuIterm")
@RestController("WarehouseAreaSkuItermController")
@RequestMapping("warehouseSkuIterm/admin/warehouseSkuIterm")
@RequiredArgsConstructor
@Slf4j
public class WarehouseAreaSkuItermController {

    @Autowired
    private WarehouseAreaSkuItermService warehouseAreaSkuItermService;

    @ApiOperation(value = "料箱存货明细列表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<WarehouseSkuItermVo> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            String skuCode,
            String skuName,
            Long shelfId,Long warehouseId,Long warehouseAreaId,Long warehouseShelfSpaceId,String shelfSpaceCode) {


        Page<WarehouseSkuItermVo> pg = new Page<>(page, limit);
        Map<String, Object> map = new HashMap();
        map.put("skuCode", skuCode);
        map.put("skuName", skuName);

        map.put("shelfId", shelfId);
        map.put("warehouseId", warehouseId);
        map.put("warehouseAreaId", warehouseAreaId);
        map.put("warehouseShelfSpaceId", warehouseShelfSpaceId);
        map.put("shelfSpaceCode", shelfSpaceCode);
        IPage<WarehouseSkuItermVo> list = warehouseAreaSkuItermService.list4app(pg, map);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "修改库位存货信息", notes = "修改库位存货信息")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PutMapping("/updateStockSkuInfo")
    public JsonResult updateStockSkuInfo(@RequestBody WarehouseSkuItermVo warehouseSkuItermVo) {

        if(StringUtils.isBlank(warehouseSkuItermVo.getSkuName())){
            return JsonResult.fail("物料名称为空");
        }

        if(StringUtils.isBlank(warehouseSkuItermVo.getSkuCode())){
            return JsonResult.fail("物料编码为空");
        }

        int result = warehouseAreaSkuItermService.updateStockSkuInfo(warehouseSkuItermVo);
        if (result > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }

    @ApiOperation(value = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       String skuCode,
                       String skuName,
                       Long shelfId, Long warehouseId, Long warehouseAreaId, Long warehouseShelfSpaceId){
        List<WarehouseSkuExportVO> list = new ArrayList<>();
        Map params = new HashMap();

        if(StringUtils.isNotBlank(skuCode)){
            params.put("skuCode", skuCode);
        }

        if(StringUtils.isNotBlank(skuName)){
            params.put("skuName", skuName);
        }

        if(shelfId!=null){
            params.put("shelfId", shelfId);
        }
        params.put("warehouseShelfSpaceId",warehouseShelfSpaceId);
        params.put("warehouseId",warehouseId);
        params.put("warehouseAreaId",warehouseAreaId);
        list = warehouseAreaSkuItermService.listExport(params);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = sdf.format(new Date());
        // 生成带时间戳的文件名
        String fileName = "库存库位导出_" + timestamp;
        ExcelUtils.export(response,fileName,list, ProductVO.class);
    }


    @ApiOperation(value = "根据skuCode查询skuCode对应的库位", notes = "搜索")
    @GetMapping("/getSkuShelfSpaceCode")
    public JsonResult getSkuShelfSpaceCode(
            String skuCode ) {
        Map<String, Object> map = new HashMap();
        map.put("skuCode", skuCode);
        if(StringUtils.isBlank(skuCode)){
            return JsonResult.fail("请填写skuCode");
        }
        return JsonResult.success(warehouseAreaSkuItermService.getSkuShelfSpaceCode(map));
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<WarehouseSkuItermExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<WarehouseSkuItermExcelIn> list = reader.read(is, WarehouseSkuItermExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            warehouseAreaSkuItermService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

}
